package star.servlet_2;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.Date;


/**
 * cookie一般会保存在本地用户目录下appdata。
 * 1.一个cookie只能存一个信息
 * 2.一个web站点可以给浏览器发送多个cookie，最多存放20个
 * 3.cookie大小有限制4kb
 * 4.浏览器上限300个cookie
 *
 * 删除cookie
 * 1.不设置有效期，关闭浏览器即消失
 * 2.设置有效时间为0
 */
//保存用户上次访问的时间
public class Cookie_11 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //服务器告诉你刚来的时间，把这个时间封装成一个信件就可以了
        //解决中文乱码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();

        //Cookie 服务器从客户端获取
        Cookie[] cookie = req.getCookies();//返回数组，说明cookie可能有多个

        if(cookie!=null){
            out.write("上次访问的时间是：");

            for (int i=0;i<cookie.length;i++) {
                Cookie ck = cookie[i];
                //获取cookie的值
                if(ck.getName().equals("lastLoginTime"))
                {
                    Long lastLoginTime = Long.parseLong(ck.getValue());
                    Date date = new Date(lastLoginTime);
                    out.write(date.toLocaleString());
                }
            }
        }else {
            out.print("第一次访问");
        }

        //服务给客户端响应一个Cookie
        Cookie ck = new Cookie("lastLoginTime",System.currentTimeMillis()+"");

        /**
         * 保证cookie安全性的编码解码
         * URLEncoder.encode("星星！","utf-8");
         * URLDecoder.decode(ck.getValue(),"utf-8");
         */



        //设置有效期为一天
        ck.setMaxAge(24*60*60);
        resp.addCookie(ck);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
